package cn.psvmc.cxzapi.interceptors;

import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.util.JedisUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {
    @Value("${sys.whitelistAPI}")
    private String whitelistAPI;
    @Resource
    private JedisUtil jedisUtil;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) {

    }

    /**
     * 在调用controller具体方法前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //log.info("请求的uri:" + request.getRequestURI());
        //response.setHeader("Access-Control-Allow-Origin", "*");//WebMvcConfg已经设置了跨越，重复设置失效
        response.setContentType("application/json;charset=UTF-8");

        // 记录请求开始时间
        //request.setAttribute("_startTime", System.currentTimeMillis());
        String requestURI = request.getRequestURI();
//        log.info("请求的uri:" + requestURI);
        String key = request.getHeader("Cxz-Token-Key");
        String token = request.getHeader("Cxz-Token-Value");
        boolean rtn = ToolUtils.whiteAPI(requestURI, whitelistAPI);
        if (!rtn) {//非白名单接口验证token
            String redis_token = jedisUtil.get(key);//系统缓存中保存的token
            if (ToolUtils.isEmpty(token) || !token.equals(redis_token)) {
                Result result = new Result();
                result.setCode(2);
                result.setMsg("登录失效");

                response.getWriter().print(JSON.toJSONString(result));
                return false;
            } else {
                jedisUtil.refreshToken(key, redis_token);//刷新token
            }
        }
        return true;
    }
}
